package cn.Thread;

import java.util.ArrayList;
import java.util.List;

/**
 * &#064;Time 2024 五月 星期四 22:21
 *
 * @author ShangGuan
 */
public class Account {


    private long money;


    public synchronized void transfer(Account account, long money) {
        if (this.money >= money) {
            this.money -= money;
            account.money += money;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Allocator allocator = new Allocator();
        Account a = new Account();
        Account b = new Account();
        a.money = 200;
        a.transfer(b, 100);
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                allocator.apply(a,b);
                a.transfer(b, 100);
                System.out.println("我是线程1");
                allocator.free(a,b);
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                allocator.apply(a,b);
                a.transfer(b, 100);
                System.out.println("我是线程2");
                allocator.free(a,b);
            }
        });
        threadA.start();
        threadB.start();

    }

    static  class Allocator {
        private final List<Object> als = new ArrayList<>();

        // 一次性申请所有资源
        synchronized void apply(Object from, Object to) {
            // 经典写法
            while (als.contains(from) || als.contains(to)) {
                try {
                    wait();
                } catch (Exception e) {
                }
            }
            als.add(from);
            als.add(to);
        }

        // 归还资源
        synchronized void free(Object from, Object to) {
            als.remove(from);
            als.remove(to);
            notifyAll();
        }
    }
}
